﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using eloamComLib;
using System.Globalization;
using System.Timers;
using System.Threading;
using System.Text.RegularExpressions;
using System.Data.Entity;
using System.Net;
using System.Configuration;

//using MSword = Microsoft.Office.Interop.Word;
//using Microsoft.Office.Interop.Word;


namespace BRS.BidModule
{
    public partial class frmBid : Form
    {
        //private Sunisoft.IrisSkin.SkinEngine skinEngine1;
        Entities brs = new Entities();
        static string Dir = ConfigurationManager.AppSettings["ip"];
        static string ServerUser = ConfigurationManager.AppSettings["user"];
        static string ServerPassword = ConfigurationManager.AppSettings["password"];
        static string filepath = ConfigurationManager.AppSettings["filepath"];

        //config.AppSettings.Settings["path"].Value = "xiey4353455c";
        //brsContext brs = new brsContext();
        private EloamGlobal global;
        private EloamVideo video;
        Users people = new Users();//全局变量，创建用户

        private EloamImage globalTempImage;
        public EloamMemory m_pTemplate;
        public EloamMemory m_pFeature;

        //int devIdx; 
        int resIdx = 0;
        //int modeIdx;
        bool hasClickOcrList = false;
        string picturename = "";
        string docname = "";

        string Comp = "";   //企业名称
        string CompCode = "";   //企业编号 
        string Corp = "";   ///法人代表       
        string IDCODE = ""; ////法人证件      
        string Pho = ""; ///手机号码  这是字符串结尾

        //法定代表人Corp
        string CorpName = "";
        string CorpIdCode = "";
        string CorpPhone = "";
        //企业负责人CompCharge
        string CompChargeName = "";
        string CompChargeIdCode = "";
        string CompChargePhone = "";
        //企业技术负责人CompTech       
        string CompTechName = "";
        string CompTechIdCode = "";
        string CompTechPhone = "";
        //项目负责人ProjectCharge
        string ProjectChargeName = "";
        string ProjectChargeIdCode = "";
        string ProjectChargePhone = "";


        string BidderPath = "";   ///投标人信息文件路径
        string Idfile = "";//身份证图片路径
        string Identityproof = "";//身份证明地址
        string IdproPicture = "";
        Regex reg = new Regex("[^(A-Za-z)|^(0-9)|^(\u4e00-\u9fa5)]");//正则表达式，除去除汉字，字母，数字的其他字符
        //设备列表
        private List<EloamDevice> deviceList;

        int CurrentSelect = 0;

        /// <summary>
        /// 进度条参数
        /// 初始值为0，每完成一个步骤加1
        /// 共分为三个步骤
        /// 第一个为身份证明
        /// 第二个为二代身份证识别
        /// 第三个为现场照采集完成
        /// 最后可以定义一个标示，为
        /// </summary>
        //int pbar1 = 0;//法定代表人
        //int pbar2 = 0;//企业负责人
        //int pbar3 = 0;//企业技术负责人
        //int pbar4 = 0;//项目负责人
        //int AllDone = 0;//定义完成
        //是否重试
        private bool TryAgain = false;
        System.Timers.Timer LimitTime = new System.Timers.Timer(); //设置时间间隔为10秒

        public frmBid()///无参加载
        {
            InitializeComponent();
            global = new EloamGlobal();
            deviceList = new List<EloamDevice>();
            m_pFeature = null;
            m_pTemplate = null;
            FormInit();
            Init();
        }
        public frmBid(Users user)//带参数加载
        {
            InitializeComponent();
            //this.skinEngine1.SkinFile = Application.StartupPath + "//XPOrange.ssk";
            //Sunisoft.IrisSkin.SkinEngine se = null;
            //se = new Sunisoft.IrisSkin.SkinEngine();
            //se.SkinAllForm = true;
            global = new EloamGlobal();
            deviceList = new List<EloamDevice>();
            m_pFeature = null;
            m_pTemplate = null;
            people = user;//
            FormInit();
            Init();


            this.tabControl1.Controls.Remove(tabPage1);//移除签到
            this.tabControl1.Controls.Remove(tabPage2);//移除投标人管理
            this.tabControl1.Controls.Remove(tabPage3);//移除项目管理
            this.tabControl1.Controls.Remove(tabPage4);//移除用户管理
            this.tabControl1.Controls.Remove(tabPage5);//移除角色管理
            this.tabControl1.Controls.Remove(tabPage6);//移除权限管理
            this.tabControl1.Controls.Remove(tabPage7);//移除权限管理
            //this.addprojectbtn.Enabled = false;
            ///在这里写权限事件
            ///
            var userrole = brs.UserRoles.Where(p => p.uid == user.UserId).Select(p => p.rid).ToList();
            var roleright = brs.RoleRights.Where(p => userrole.Contains(p.rid)).Select(p => p.riid).ToList();
            var rights = brs.Rights.Where(p => roleright.Contains(p.Id)).ToList();
            foreach (var p in rights)
            {
                if (p.Module.ToString().ToLower() == "tabpage1") this.tabControl1.TabPages.Add(tabPage1);////添加签到
                if (p.Module.ToString().ToLower() == "tabpage2") this.tabControl1.TabPages.Add(tabPage2);////添加投标人管理
                if (p.Module.ToString().ToLower() == "tabpage3") this.tabControl1.TabPages.Add(tabPage3);////添加项目管理
                if (p.Module.ToString().ToLower() == "tabpage4") this.tabControl1.TabPages.Add(tabPage4);////添加用户管理
                if (p.Module.ToString().ToLower() == "tabpage5") this.tabControl1.TabPages.Add(tabPage5);////添加角色管理
                if (p.Module.ToString().ToLower() == "tabpage6") this.tabControl1.TabPages.Add(tabPage6);////添加权限管理
                if (p.Module.ToString().ToLower() == "tabpage7") this.tabControl1.TabPages.Add(tabPage7);////添加权限管理
                //if (p.btn.ToString().ToLower() == "addprojectbtn") this.addprojectbtn.Enabled = true;//新增项目
            }
            //button2.Enabled = false;

        }
        public void FormInit()
        {
            //传入设备状态改变事件
            global.DevChange += DevChangeEventHandler;
            //传入移动监测事件
            global.MoveDetec += MoveDetecEventHandler;
            //视频播放事件
            global.Arrival += ArrivalEventHandler;
            //二代证
            global.IdCard += IdCardEventHandler;
            //Ocr识别事件
            global.Ocr += OcrEventHandler;

            //初始化设备
            global.InitDevs();

            if (!global.InitIdCard())
            {
                //button_StartIdCardRead.Enabled = false;
                //button_StopReadIDCard.Enabled = false;
            }


            if (global.InitOcr())
            {
                ocr.Enabled = true;
                //ocrList.Enabled = true;
            }

            this.pager1.PageCurrent = 1;//当前页为第一页  
            pager1.PageSize = 20;//页数  
            this.pager1.Bind();//绑定

            this.pager2.PageCurrent = 1;//当前页为第一页  
            pager2.PageSize = 20;//页数  
            this.pager2.Bind();//绑定 


            this.pager3.PageCurrent = 1;//当前页为第一页  
            pager3.PageSize = 20;//页数  
            this.pager3.Bind();//绑定
            binds();
            // this.tabPage1.Parent = null; ;

        }

        private void binds()////绑定数据
        {
            dGVRight.AutoGenerateColumns = false;
            dGVUser.AutoGenerateColumns = false;
            dataGridView1.AutoGenerateColumns = false;
            //dGVUserRole.AutoGenerateColumns = false;
            dataGridView2.AutoGenerateColumns = false;

            comboBox1.DisplayMember = "ProjectName";//控件显示的列名  
            comboBox1.ValueMember = "ProjectCode";//控件值的列名  

            comboBox1.DataSource = brs.tb_Project.Where(p => p.Enabled == true && p.Deaddate > DateTime.Today && p.TenderAgent.ToString() == people.UserName.ToString()).ToList();
            dgv1binds();
            dgv2binds();
            dgv3binds();
            //dataGridView1.DataSource = brs.tb_Bidder.ToList();
            //dataGridView2.DataSource = brs.tb_Project.OrderBy(p => p.CreateDate).ToList();
            dGVUser.DataSource = brs.Users.AsNoTracking().ToList();
            dGVRole.DataSource = brs.Roles.ToList();
            dGVRight.DataSource = brs.Rights.ToList();
        }
        private int pager1_EventPaging(BRS.BidModule.EventPagingArg e)
        {
            return dgv1binds();
        }

        private int pager2_EventPaging(BRS.BidModule.EventPagingArg e)
        {
            return dgv2binds();
        }
        private int pager3_EventPaging(BRS.BidModule.EventPagingArg e)
        {
            return dgv3binds();
        }

        public int dgv1binds()
        {
            dataGridView1.AutoGenerateColumns = false;
            int start = 0;
            //if (pager1.PageCurrent > 0)
            {
                start = (pager1.PageSize * (pager1.PageCurrent - 1) + 1);
            }

            int end = (pager1.PageSize * pager1.PageCurrent);
            int count = brs.tb_Bidder.Count();
            if (count > 0)
            {
                if (!String.IsNullOrEmpty(textBox15.Text))
                {
                    //count = brs.tb_Bidder.Where(p => p.Company.Contains(textBox15.Text) || p.CompanyCode.Contains(textBox16.Text)).Count();
                    count = brs.tb_Bidder.Where(p => p.Company.Contains(textBox15.Text)).Count();
                    dataGridView1.DataSource = brs.tb_Bidder.Where(p => p.Company.Contains(textBox15.Text)).OrderBy(p => p.CreateDate).Skip(start - 1).Take(pager1.PageSize).AsNoTracking().ToList();
                }
                else dataGridView1.DataSource = brs.tb_Bidder.OrderBy(p => p.CreateDate).Skip(start - 1).Take(pager1.PageSize).AsNoTracking().ToList();
            }
            return count;
        }
        public int dgv2binds()
        {
            dataGridView2.AutoGenerateColumns = false;
            int start = 0;
            //if (pager2.PageCurrent > 0)
            {
                start = (pager2.PageSize * (pager2.PageCurrent - 1) + 1);
            }
            int end = (pager2.PageSize * pager2.PageCurrent);
            int count = brs.tb_Project.Count();
            if (count > 0)
            {
                if (!String.IsNullOrEmpty(txtBoxProjectName.Text))
                {
                    count = brs.tb_Project.Where(p => p.ProjectName.Contains(txtBoxProjectName.Text)).Count();
                    dataGridView2.DataSource = brs.tb_Project.Where(p => p.ProjectName.Contains(txtBoxProjectName.Text)).OrderBy(p => p.CreateDate).Skip(start - 1).Take(pager2.PageSize).AsNoTracking().ToList();
                }
                else
                {
                    dataGridView2.DataSource = brs.tb_Project.OrderBy(p => p.CreateDate).Skip(start - 1).Take(pager2.PageSize).AsNoTracking().ToList();
                }

            }
            return count;
        }
        public int dgv3binds()
        {
            dGVTender.AutoGenerateColumns = false;
            int start = 0;
            //if (pager3.PageCurrent > 0)
            {
                start = (pager3.PageSize * (pager3.PageCurrent - 1) + 1);
            }
            int end = (pager3.PageSize * pager3.PageCurrent);
            int count = brs.TenderMsg.Count();
            if (count > 0)
            {
                if (!String.IsNullOrEmpty(txt_TenderMsgName.Text))
                {
                    count = brs.TenderMsg.Where(p => p.Name.Contains(txt_TenderMsgName.Text)).Count();
                    dGVTender.DataSource = brs.TenderMsg.Where(p => p.Name.Contains(txt_TenderMsgName.Text)).OrderBy(p => p.AddTime).Skip(start - 1).Take(pager3.PageSize).AsNoTracking().ToList();
                }
                else dGVTender.DataSource = brs.TenderMsg.OrderBy(p => p.AddTime).Skip(start - 1).Take(pager3.PageSize).AsNoTracking().ToList();

            }
            return count;
        }
        private void openProperty_Click(object sender, EventArgs e)
        {
            if (null != video)
            {
                EloamDevice tempDevice = (EloamDevice)video.GetDevice();
                tempDevice.ShowProperty(eloamView.GetView());
            }
        }
        #region demo存在，关闭form
        private void frmBid_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeVideo_Click(new object(), new EventArgs());

            int count = deviceList.Count;
            if (count != 0)
            {
                for (int i = 0; i < count; i++)
                {
                    deviceList[i].Destroy();
                }
            }
            deviceList.Clear();

            global.DeinitBarcode();

            if (null != m_pTemplate)
            {
                m_pTemplate.Destroy();
                m_pTemplate = null;
            }
            if (null != m_pFeature)
            {
                m_pFeature.Destroy();
                m_pFeature = null;
            }

            global.DeinitBiokey();
            global.DeinitIdCard();
            global.DeinitDevs();
            global.DeinitOcr();

            global = null;
            //System.Windows.Forms.Application.Exit();
        }
        #endregion
        //设备状态改变事件响应
        #region 设备状态改变事件
        public void DevChangeEventHandler(int type, int idx, int dbt)
        {
            if (1 == type)
            {
                if (1 == dbt)//设备到达
                {
                    EloamDevice tempDevice = (EloamDevice)global.CreateDevice(1, idx);
                    deviceList.Add(tempDevice);
                    string Name1 = "文件扫描/拍摄";
                    string Name2 = "现场照";
                    if (tempDevice.GetFriendlyName() == "S620A3AF")
                    {
                        selectDevice.Items.Add(Name1);
                        //selectDevice.SelectedValue=0;
                    }
                    else if (tempDevice.GetFriendlyName() == "USB CAM2")
                    {
                        selectDevice.Items.Add(Name2);
                        //selectDevice.SelectedValue = 1;
                    }

                    if (-1 == selectDevice.SelectedIndex)
                    {
                        selectDevice.SelectedIndex = 0;//改变所选设备
                    }

                }
                else if (2 == dbt)//设备丢失
                {
                    EloamDevice tempDevice = deviceList[idx];
                    if (null != video)
                    {
                        EloamDevice tempDevice2 = (EloamDevice)video.GetDevice();
                        if (tempDevice == tempDevice2)
                        {
                            closeVideo_Click(new object(), new EventArgs());
                        }
                    }

                    deviceList[idx].Destroy();
                    deviceList.RemoveAt(idx);
                    selectDevice.Items.RemoveAt(idx);
                    if (-1 == selectDevice.SelectedIndex)
                    {
                        if (0 != deviceList.Count)
                        {
                            selectDevice.SelectedIndex = 0;
                        }
                    }
                }
            }
        }
        #endregion

        #region //二代证事件响应
        public void IdCardEventHandler(int ret)
        {
            FtpWeb ftpweb = new FtpWeb(Dir, "投标人信息", ServerUser, ServerPassword);
            /////重点选取编号为1，8的身份证信息：姓名，身份证号
            string time = DateTime.Now.ToString(
                  "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            /// 数字1表示头像，2表示正面，3反面，4表示正反垂直合成，5表示反正垂直合成，6表示正反水平合成，7表示反正水平合成
            var tempImg = global.GetIdCardImage(4);
            string uppath = "";//上传路径

            //BidderPath = @pictureSavePath.Text + "投标人信息/" + Comp;
            //if (!Directory.Exists(BidderPath))
            //{
            //    Directory.CreateDirectory(BidderPath);
            //}
            if (Comp != "")
            {
                if (!ftpweb.DirectoryExist(Comp))//文件服务器创建目录
                {
                    ftpweb.MakeDir(Comp);
                }

                string[] list4 = { "法定代表人", "企业负责人", "企业技术负责人", "项目负责人" };
                foreach (var p in list4)
                {
                    string path = "投标人信息/" + Comp + "/" + p;
                    BidderPath = @pictureSavePath.Text + path;
                    if (!Directory.Exists(BidderPath))
                    {
                        Directory.CreateDirectory(BidderPath);//本地创建目录
                    }

                    if (!ftpweb.DirectoryExist(Comp + "/" + p))//文件服务器创建目录
                    {
                        ftpweb.MakeDir(Comp + "/" + p);
                    }

                }

                //Idfile = pictureSavePath.Text + "投标人信息/" + Comp + "/证件" + CompCode + "_" + time + ".jpg";
                if (Identityproof != "")
                {
                    switch (Identityproof.Substring(0, 5))
                    {
                        case "法定代表人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/法定代表人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/法定代表人"; break;
                        case "企业负责人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/企业负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业负责人"; break;
                        case "企业技术负": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/企业技术负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业技术负责人"; break;
                        case "项目负责人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/项目负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/项目负责人"; break;

                    }
                    switch (CurrentSelect)
                    {
                        case 1: if (progressBar1.Value == 30) progressBar1.Value += 40; break;
                        case 2: if (progressBar2.Value == 30) progressBar2.Value += 40; break;
                        case 3: if (progressBar3.Value == 30) progressBar3.Value += 40; break;
                        case 4: if (progressBar4.Value == 30) progressBar4.Value += 40; break;

                    }
                }


                ///上传图片
                if (tempImg.Save(IdproPicture, 0))
                {

                    FileInfo fileinfo = new FileInfo(IdproPicture);
                    ftpweb.Dir(uppath);
                    if (!ftpweb.FileExist("身份证" + Identityproof + time + ".jpg"))//验证服务器是否存在此文件
                    {
                        ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                    }
                    else
                    {
                        ftpweb.Delete("身份证" + Identityproof + time + ".jpg");
                        ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                    }
                    //ftpweb.UploadFile(fileinfo, uppath);
                    IDfrm idpicture = new IDfrm(IdproPicture);
                    idpicture.ShowDialog();//弹窗显示身份证图片
                    if (idpicture.DialogResult == System.Windows.Forms.DialogResult.OK)
                    {
                        global.StopIdCardDiscern();
                        openCam_Click(null, null);
                    }
                    LimitTime = null;
                    TryAgain = false;
                }
                else MessageBox.Show("识别失败！");
            }
        }
        #endregion
        //public void IDtophoto(object sender, EventArgs e)
        //{
        //    FtpWeb ftpweb = new FtpWeb(Dir, "投标人信息", ServerUser, ServerPassword);
        //    /////重点选取编号为1，8的身份证信息：姓名，身份证号
        //    string time = DateTime.Now.ToString(
        //          "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
        //    /// 数字1表示头像，2表示正面，3反面，4表示正反垂直合成，5表示反正垂直合成，6表示正反水平合成，7表示反正水平合成
        //    var tempImg = global.GetIdCardImage(4);
        //    string uppath = "";//上传路径

        //    //BidderPath = @pictureSavePath.Text + "投标人信息/" + Comp;
        //    //if (!Directory.Exists(BidderPath))
        //    //{
        //    //    Directory.CreateDirectory(BidderPath);
        //    //}
        //    if (Comp != "")
        //    {
        //        if (!ftpweb.DirectoryExist(Comp))//文件服务器创建目录
        //        {
        //            ftpweb.MakeDir(Comp);
        //        }

        //        string[] list4 = { "法定代表人", "企业负责人", "企业技术负责人", "项目负责人" };
        //        foreach (var p in list4)
        //        {
        //            string path = "投标人信息/" + Comp + "/" + p;
        //            BidderPath = @pictureSavePath.Text + path;
        //            if (!Directory.Exists(BidderPath))
        //            {
        //                Directory.CreateDirectory(BidderPath);//本地创建目录
        //            }

        //            if (!ftpweb.DirectoryExist(Comp + "/" + p))//文件服务器创建目录
        //            {
        //                ftpweb.MakeDir(Comp + "/" + p);
        //            }

        //        }

        //        //Idfile = pictureSavePath.Text + "投标人信息/" + Comp + "/证件" + CompCode + "_" + time + ".jpg";
        //        if (Identityproof != "")
        //        {
        //            switch (Identityproof.Substring(0, 5))
        //            {
        //                case "法定代表人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/法定代表人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/法定代表人"; break;
        //                case "企业负责人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/企业负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业负责人"; break;
        //                case "企业技术负": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/企业技术负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业技术负责人"; break;
        //                case "项目负责人": IdproPicture = pictureSavePath.Text + "投标人信息/" + Comp + "/项目负责人" + "/身份证" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/项目负责人"; break;

        //            }
        //            switch (CurrentSelect)
        //            {
        //                case 1: if (progressBar1.Value == 30) progressBar1.Value += 40; break;
        //                case 2: if (progressBar2.Value == 30) progressBar2.Value += 40; break;
        //                case 3: if (progressBar3.Value == 30) progressBar3.Value += 40; break;
        //                case 4: if (progressBar4.Value == 30) progressBar4.Value += 40; break;

        //            }
        //        }


        //        ///上传图片
        //        if (tempImg.Save(IdproPicture, 0))
        //        {

        //            FileInfo fileinfo = new FileInfo(IdproPicture);
        //            ftpweb.UploadFile(fileinfo, uppath);
        //            IDfrm idpicture = new IDfrm(IdproPicture);
        //            idpicture.ShowDialog();//弹窗显示身份证图片
        //            if (idpicture.DialogResult == System.Windows.Forms.DialogResult.OK)
        //            {
        //                openCam_Click(sender, e);
        //                //shoot_Click(object sender, EventArgs e);
        //                //shoot_Click(sender, e);
        //                //textBox1.Text = idpicture.StrValue;//获取弹出窗体的属性值
        //            }

        //        }
        //        else MessageBox.Show("识别失败！");
        //    }

        //}
        //移动监测事件响应
        public void MoveDetecEventHandler(object pVideo, int id)
        {
            // Fire_MoveDetec
            shoot_Click(new object(), new EventArgs());
        }


        #region 视频播放事件
        private void ArrivalEventHandler(object pVideo, int id)
        {
            if (0 == id)//视频第一帧
            {
                openVideo.Enabled = false;
                closeVideo.Enabled = true;
                //turnLeft.Enabled = true;
                //turnRight.Enabled = true;

                pictureSavePath.Enabled = true;
                shoot.Enabled = true;

                //barcode.Enabled = true;
            }
        }
        #endregion
        //Ocr识别事件
        private void OcrEventHandler(int flag, int ret)
        {
            if (hasClickOcrList)//只在识别列表时生效
            {
                if (1 == flag)
                {
                    if (0 == ret)
                    {
                        // richTextBox1.Text=  global.GetOcrData(1,1);
                        global.SaveOcr("F://ocrList.pdf", 0);
                        MessageBox.Show("识别成功！");
                    }
                    if (-1 == ret)
                    {
                        MessageBox.Show("识别失败！");
                    }
                    hasClickOcrList = false;
                }
                if (2 == flag)
                {
                    //OcrPercentage.Text = ret.ToString() + "%";
                }
            }
        }

        #region OCR识别图片
        private void button1_Click(object sender, EventArgs e)
        {

            if (null == video)
            {
                MessageBox.Show("视频未打开");
                return;
            }
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)video.CreateImage(0, tempView);
            if (tempImage != null)
            {

                //StringBuilder MyString = new StringBuilder();
                global.DiscernOcr(1, tempImage);
                global.WaitOcrDiscern();//同步等待
                ///OCR读取表格
                ///
                DateTime dateTime = DateTime.Now;
                bool is18 = true;
                try
                {
                    string Ocrmessage = global.GetOcrPlainText(0);
                    Ocrmessage = reg.Replace(Ocrmessage, "");
                    //MessageBox.Show(Ocrmessage);
                    ////企业名称
                    int start1 = Ocrmessage.IndexOf("投标人名称", 0);
                    int end1 = Ocrmessage.IndexOf("法定代表人", start1);
                    //int end1 = Ocrmessage.IndexOf("组织机构代码", start1);
                    Comp = Ocrmessage.Substring(start1 + 5, end1 - start1 - 5);
                    Comp = reg.Replace(Comp, "");
                    //Comp = Comp.Replace("有限贵任公司", "有限责任公司");
                    Comp = Comp.Replace("贵任公司", "责任公司");
                    ////企业编号
                    //int start2 = Ocrmessage.IndexOf("组织机构代码", 0);
                    //int end2 = Ocrmessage.IndexOf("法定代表人", start2);
                    //CompCode = Ocrmessage.Substring(start2 + 6, end2 - start2 - 6);
                    //CompCode = reg.Replace(CompCode, "");

                    string Name = @"(?<=姓名)([^a])*(?=身份证号码)";
                    string IdCode = @"(?<=身份证号码)([^a])*(?=手机号码)";
                    string PhoneNO = @"(?<=手机号码)([^a])*(?=)";


                    //法定代表人Corp 
                    int start3 = Ocrmessage.IndexOf("法定代表人", 0);
                    int end3 = Ocrmessage.IndexOf("企业负责人", start3);
                    Corp = Ocrmessage.Substring(start3 + 5, end3 - start3 - 5);
                    Corp = reg.Replace(Corp, "");
                    CorpName = Regex.Match(Corp, Name).Value;
                    CorpIdCode = Regex.Match(Corp, IdCode).Value;
                    CorpPhone = Regex.Match(Corp, PhoneNO).Value;

                    //企业负责人CompCharge
                    int start4 = Ocrmessage.IndexOf("企业负责人", 0);
                    int end4 = Ocrmessage.IndexOf("企业技术负责人", start4);
                    string CompCharge = Ocrmessage.Substring(start4 + 5, end4 - start4 - 5);
                    CompCharge = reg.Replace(CompCharge, "");
                    CompChargeName = Regex.Match(CompCharge, Name).Value;
                    CompChargeIdCode = Regex.Match(CompCharge, IdCode).Value;
                    CompChargePhone = Regex.Match(CompCharge, PhoneNO).Value;

                    //企业技术负责人CompTech
                    int start5 = Ocrmessage.IndexOf("企业技术负责人", 0);
                    int end5 = Ocrmessage.IndexOf("项目负责人", start5);
                    string CompTech = Ocrmessage.Substring(start5 + 7, end5 - start5 - 7);
                    CompTech = reg.Replace(CompTech, "");
                    CompTechName = Regex.Match(CompTech, Name).Value;
                    CompTechIdCode = Regex.Match(CompTech, IdCode).Value;
                    CompTechPhone = Regex.Match(CompTech, PhoneNO).Value;

                    //项目负责人ProjectCharge
                    int start6 = Ocrmessage.IndexOf("项目负责人", 0);
                    int end6 = Ocrmessage.IndexOf("备注", start6);
                    string ProjectCharge = Ocrmessage.Substring(start6 + 5, end6 - start6 - 5);
                    ProjectCharge = reg.Replace(ProjectCharge, "");
                    ProjectChargeName = Regex.Match(ProjectCharge, Name).Value;
                    ProjectChargeIdCode = Regex.Match(ProjectCharge, IdCode).Value;
                    ProjectChargePhone = Regex.Match(ProjectCharge, PhoneNO).Value;

                    //投标人名称
                    //组织机构代码            
                    textBox1.Text = Comp;
                    //textBox2.Text = CompCode;
                    //法定代表人
                    // CorpName
                    // CorpIdCode
                    // CorpPhone

                    textBox3.Text = CorpName;
                    textBox4.Text = CorpIdCode;
                    textBox5.Text = CorpPhone;
                    if (!String.IsNullOrEmpty(textBox4.Text) && textBox4.Text.Length != 18)
                    {
                        MessageBox.Show("识别有误，身份证识别位数不是18位！请 “修正” 或者重新  “文字识别” ！", "警告！");
                        is18 = false;
                    }
                    //企业负责人CompCharge
                    //CompChargeName  
                    //CompChargeIdCode       
                    //CompChargePhone        
                    textBox6.Text = CompChargeName;
                    textBox7.Text = CompChargeIdCode;
                    textBox8.Text = CompChargePhone;
                    if (!String.IsNullOrEmpty(textBox7.Text) && textBox7.Text.Length != 18)
                    {
                        MessageBox.Show("识别有误，身份证识别位数不是18位！请 “修正” 或者重新  “文字识别” ！", "警告！");
                        is18 = false;
                    }

                    //企业技术负责人CompTech       
                    //CompTechName  
                    //CompTechIdCode
                    //CompTechPhone 
                    textBox9.Text = CompTechName;
                    textBox10.Text = CompTechIdCode;
                    textBox11.Text = CompTechPhone;
                    if (!String.IsNullOrEmpty(textBox10.Text) && textBox10.Text.Length != 18)
                    {
                        MessageBox.Show("识别有误，身份证识别位数不是18位！请 “修正” 或者重新  “文字识别” ！", "警告！");
                        is18 = false;
                    }

                    //项目负责人ProjectCharge
                    //ProjectChargeName
                    //ProjectChargeIdCode
                    //ProjectChargePhone
                    textBox12.Text = ProjectChargeName;
                    textBox13.Text = ProjectChargeIdCode;
                    textBox14.Text = ProjectChargePhone;
                    if (!String.IsNullOrEmpty(textBox13.Text) && textBox13.Text.Length != 18)
                    {
                        MessageBox.Show("识别有误，身份证识别位数不是18位！请 “修正” 或者重新  “文字识别” ！", "警告！");
                        is18 = false;
                    }
                    //if (Comp != "" && CompCode != "") 
                    if (Comp != "" && is18 == true)
                    {
                        //button2.Enabled = true;
                        //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                        ////"确定要退出吗？"是对话框的显示信息，"退出系统"是对话框的标题
                        ////默认情况下，如MessageBox.Show("确定要退出吗？")只显示一个“确定”按钮。
                        //DialogResult dr = MessageBox.Show("确定要退出吗?", "退出系统", messButton);
                        //if (dr == DialogResult.OK)//如果点击“确定”按钮
                        //{

                        //}
                        //else//如果点击“取消”按钮
                        //{
                        //}

                        MessageBox.Show("识别成功，请检查识别信息是否正确，然后“拍摄登记表”！");
                    }
                }
                catch (Exception) { MessageBox.Show("识别失败！请调试好机器并放置好文档或者手动输入，并点击“修正”！"); }
            }

        }
        #endregion
        private void openVideo_Click(object sender, EventArgs e)
        {
            if (deviceList.Count > 0)
            {
                selectDevice.SelectedIndex = 0;
                int devIdx = selectDevice.SelectedIndex;
                //resIdx = selectResolution.SelectedIndex;
                //modeIdx = selectMode.Text == "YUY2" ? 1 : 2;
                int modeIdx = 1;
                if (devIdx == 1) modeIdx = 2;
                if (-1 != devIdx)
                {
                    if (null != video)
                    {
                        video.Destroy();
                        video = null;
                    }

                    EloamDevice tempDevice = deviceList[devIdx];
                    video = (EloamVideo)tempDevice.CreateVideo(resIdx, modeIdx);

                    if (null != video)
                    {
                        eloamView.SelectVideo(video);
                        eloamView.SetText("打开视频中，请等待...", RGB(255, 255, 255));

                        selectDevice.Enabled = false;
                        //selectResolution.Enabled = false;
                        //selectMode.Enabled = false;
                        //openCam.Enabled = true;
                        openVideo.Enabled = false;
                        closeVideo.Enabled = true;
                    }
                }
            }
            else { MessageBox.Show("请链接设备！"); }
        }
        private void closeVideo_Click(object sender, EventArgs e)
        {
            if (null != video)
            {
                eloamView.SetText(null, 0);
                video.Destroy();
                video = null;
            }

            eloamView.SetText(null, 0);

            Reset();
        }

        public uint RGB(uint r, uint g, uint b)
        {
            return (((b << 16) | (g << 8)) | r);
        }
        public void Reset()
        {
            Init();
        }
        public void Init()
        {
            selectDevice.Enabled = true;
            //selectResolution.Enabled = true;
            //selectMode.Enabled = true;
            //openCam.Enabled = true;
            openVideo.Enabled = true;
            closeVideo.Enabled = false;
            //turnLeft.Enabled = false;
            //turnRight.Enabled = false;

            pictureSavePath.Enabled = false;
            shoot.Enabled = false;
            pictureSavePath.Text = filepath;//"E:\\";

        }

        #region 拍摄图片
        private void shoot_Click(object sender, EventArgs e)
        {
            FtpWeb ftpweb = new FtpWeb(Dir, "投标人信息", ServerUser, ServerPassword);
            string uppath = "";
            //string ShowMessage = "";
            if (Comp != "") uppath = "投标人信息/" + Comp;
            if (null == video)
            {
                return;
            }
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)video.CreateImage(0, tempView);

            if (null != tempImage)
            {
                string time = DateTime.Now.ToString(
                           "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
                picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/扫描" + CompCode + ".jpg";
                if (Comp != "")
                {

                    //MessageBox.Show(Comp);
                    if (!ftpweb.DirectoryExist(Comp))//文件服务器创建目录  主目录
                    {
                        ftpweb.MakeDir(Comp);
                    }

                    /////分别创建本地和服务器目录

                    string[] list4 = { "法定代表人", "企业负责人", "企业技术负责人", "项目负责人" };
                    foreach (var p in list4)
                    {
                        string path = "投标人信息/" + Comp + "/" + p;
                        BidderPath = @pictureSavePath.Text + path;
                        if (!Directory.Exists(BidderPath))
                        {
                            Directory.CreateDirectory(BidderPath);//本地创建目录
                        }
                        // UpDownLoad.MakeDir(path, Dir, ServerUser, ServerPassword); 

                        string ServerPath = @Dir + path;

                        if (!ftpweb.DirectoryExist(Comp + "/" + p))//文件服务器创建目录 次目录
                        {
                            ftpweb.MakeDir(Comp + "/" + p);
                        }

                    }



                    if (selectDevice.SelectedIndex == 0)
                    {
                        picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/扫描" + "_" + time + ".jpg";
                        if (Identityproof != "")
                        {
                            switch (Identityproof.Substring(0, 5))
                            {
                                case "法定代表人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/法定代表人" + "/证明" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/法定代表人"; break;
                                case "企业负责人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/企业负责人" + "/证明" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业负责人"; break;
                                case "企业技术负": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/企业技术负责人" + "/证明" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业技术负责人"; break;
                                case "项目负责人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/项目负责人" + "/证明" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/项目负责人"; break;

                            }

                            switch (CurrentSelect)
                            {
                                case 1: if (progressBar1.Value == 0) progressBar1.Value += 30; break;
                                case 2: if (progressBar2.Value == 0) progressBar2.Value += 30; break;
                                case 3: if (progressBar3.Value == 0) progressBar3.Value += 30; break;
                                case 4: if (progressBar4.Value == 0) progressBar4.Value += 30; break;

                            }
                            //ShowMessage = "身份证明拍摄成功，请点击“启动二代身份证”按钮！";
                        }
                        else
                        {
                            //ShowMessage = "登记表拍摄成功，请点击“新增”按钮！";
                        }


                    }
                    else if (selectDevice.SelectedIndex == 1)
                    {
                        picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/现场" + CompCode + "_" + time + ".jpg";
                        if (Identityproof != "")
                        {
                            switch (Identityproof.Substring(0, 5))
                            {
                                case "法定代表人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/法定代表人" + "/现场" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/法定代表人"; break;
                                case "企业负责人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/企业负责人" + "/现场" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业负责人"; break;
                                case "企业技术负": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/企业技术负责人" + "/现场" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/企业技术负责人"; break;
                                case "项目负责人": picturename = pictureSavePath.Text + "投标人信息/" + Comp + "/项目负责人" + "/现场" + Identityproof + time + ".jpg"; uppath = "投标人信息/" + Comp + "/项目负责人"; break;

                            }
                            switch (CurrentSelect)
                            {
                                case 1: if (progressBar1.Value == 70) progressBar1.Value += 30; break;
                                case 2: if (progressBar2.Value == 70) progressBar2.Value += 30; break;
                                case 3: if (progressBar3.Value == 70) progressBar3.Value += 30; break;
                                case 4: if (progressBar4.Value == 70) progressBar4.Value += 30; break;

                            }
                            //ShowMessage = "现场照片拍摄成功！";
                        }
                    }
                }
                if (tempImage.Save(picturename, 0))
                {
                    FileInfo fileinfo = new FileInfo(picturename);
                    ftpweb.Dir(uppath);
                    //MessageBox.Show(uppath);
                    if (Identityproof != "")//区分是否选中特定人员
                    {
                        if (selectDevice.SelectedIndex == 0)//根据摄像头判断状态
                            if (!ftpweb.FileExist("证明" + Identityproof + time + ".jpg"))//验证服务器是否存在此文件
                            {
                                ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                            }
                            else
                            {
                                ftpweb.Delete("证明" + Identityproof + time + ".jpg");
                                ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                            }
                        if (selectDevice.SelectedIndex == 1)//根据摄像头判断状态
                            if (!ftpweb.FileExist("现场" + Identityproof + time + ".jpg"))//验证服务器是否存在此文件
                            {
                                ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                            }
                            else
                            {
                                ftpweb.Delete("现场" + Identityproof + time + ".jpg");
                                ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                            }
                    }
                    else//未选中 ，是拍摄登记表
                    {
                        if (!ftpweb.FileExist("扫描" + "_" + time + ".jpg"))//验证服务器是否存在此文件 "/扫描" + "_" + time + ".jpg";
                            ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                        else
                        {
                            ftpweb.Delete("扫描" + "_" + time + ".jpg");
                            ftpweb.UploadFile(fileinfo, uppath);//传到指定路径
                        }
                    }
                    eloamView.PlayCaptureEffect();
                    int ct = eloamThumbnail.GetCount();
                    if (ct > 20)///删除超过14个的图片
                        for (int i = 6; i >= 0; i--)
                        {
                            eloamThumbnail.Remove(i, false);
                        }
                    ct = eloamThumbnail.GetCount();
                    if (ct > 0)
                    {
                        FileInfo Thumbnail = new FileInfo(eloamThumbnail.GetFileName(ct - 1));///得到当前图片名
                        FileInfo picn = new FileInfo(picturename);///得到拍摄的图片名
                        if (Thumbnail.Name == picn.Name) eloamThumbnail.Remove(ct - 1, false);///若是相同，则删除之前的，取最新
                    }
                    eloamThumbnail.Add(picturename);
                    if (Identityproof == "")
                    {

                        MessageBoxButtons messButton = MessageBoxButtons.OK;
                        //"确定要退出吗？"是对话框的显示信息，"退出系统"是对话框的标题
                        //默认情况下，如MessageBox.Show("确定要退出吗？")只显示一个“确定”按钮。
                        DialogResult dr = MessageBox.Show("新增单位信息!", "确定", messButton);
                        if (dr == DialogResult.OK)//如果点击“确定”按钮
                        {
                            this.button2_Click(sender, e);
                        }
                        else//如果点击“取消”按钮
                        {
                        }

                    }
                    else
                    {
                        if (selectDevice.SelectedIndex == 0)
                        {
                            MessageBoxButtons messButton = MessageBoxButtons.OK;
                            //默认情况下，如MessageBox.Show("确定要退出吗？")只显示一个“确定”按钮。
                            DialogResult dr = MessageBox.Show("身份证明拍摄成功，请准备放置二代身份证", "确定", messButton);
                            if (dr == DialogResult.OK)//如果点击“确定”按钮
                            {
                                IdTimerFun(null, null);
                                global.DiscernIdCard();

                            }
                        }
                        else
                            if (selectDevice.SelectedIndex == 1)
                        {
                            ///
                            /////
                            ///完成后的初始化变量
                            if (
                                  ((progressBar1.Visible == true && progressBar1.Value == 100) || String.IsNullOrEmpty(this.textBox3.Text))//确认完成每个操作
                               && ((progressBar2.Visible == true && progressBar2.Value == 100) || String.IsNullOrEmpty(this.textBox6.Text))
                               && ((progressBar3.Visible == true && progressBar3.Value == 100) || String.IsNullOrEmpty(this.textBox9.Text))
                               && ((progressBar4.Visible == true && progressBar4.Value == 100) || String.IsNullOrEmpty(this.textBox12.Text))
                                )
                            {
                                MessageBox.Show("您已经完成该单位的录入工作，点击完成按钮！");
                                button13.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("录入未完成，请继续点击“特定人员”下的按钮完成操作！");

                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                }
            }

        }
        #endregion
        /// <summary>
        /// 身份证计时器  默认10秒钟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdTimerFun(object sender, EventArgs e)
        {
            LimitTime = null;
            //仅仅此处设置为true
            TryAgain = true; 
            LimitTime = new System.Timers.Timer(10000);   //实例化Timer类，设置间隔时间为10000毫秒；   
            LimitTime.Elapsed += new System.Timers.ElapsedEventHandler(thein); //到达时间的时候执行事件；   
            LimitTime.AutoReset = false;   //设置是执行一次（false）还是一直执行(true)；   
            LimitTime.Enabled = true;     //是否执行System.Timers.Timer.Elap
        }
        public void thein(object source, System.Timers.ElapsedEventArgs e)
        {

            if (TryAgain == true)
            {
                MessageBoxButtons messButton = MessageBoxButtons.RetryCancel;
                DialogResult dr = MessageBox.Show("超过默认时间，需要重试? \n按取消则跳过进入下一步！", "重试", messButton);
                if (dr == DialogResult.Retry)//如果点击“确定”按钮
                {         
                    IdTimerFun(null, null);
                }
                else//如果点击“取消”按钮，则跳过次步骤
                {
                    LimitTime = null;
                    if (Identityproof != "")
                    {
                        switch (CurrentSelect)
                        {
                            case 1: if (progressBar1.Value == 30) progressBar1.Value += 40; break;
                            case 2: if (progressBar2.Value == 30) progressBar2.Value += 40; break;
                            case 3: if (progressBar3.Value == 30) progressBar3.Value += 40; break;
                            case 4: if (progressBar4.Value == 30) progressBar4.Value += 40; break;
                        }
                    }
                    global.StopIdCardDiscern();
                    openCam_Click(null, null);
                    TryAgain = false;
                    //MessageBox.Show("下一步1！");
                }
            }
            else//如果点击“取消”按钮
            {
                TryAgain = false;
                LimitTime = null;
                //MessageBox.Show("下一步2！");
            }
        }
        private void selectDevice_SelectedIndexChanged(object sender, EventArgs e)
        {

            int idx = selectDevice.SelectedIndex;//记录当前所选设备

            //selectMode.Items.Clear();
            //selectResolution.Items.Clear();
            //MessageBox.Show(idx.ToString());
            if (-1 != idx)
            {
                EloamDevice tempDevice = deviceList[idx];
                resIdx = 0;
                if (selectDevice.SelectedIndex == 1) resIdx = 6;//定义摄像头为2摄像头时，分辨率
                openVideo.Enabled = true;
            }
            else
            {
                openVideo.Enabled = false;
            }
        }


        private void button__Click(object sender, EventArgs e)
        {
            video.StopRecord();
        }
        private void button_record_Click(object sender, EventArgs e)
        {
            if (null != video)
            {
                video.StartRecord("F:\\eloamCom.avi", 0);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)global.CreateImageFromFile("F:\\1.jpg", 0);
            EloamImage tempImage2 = (EloamImage)global.CreateImageFromFile("F:\\2.jpg", 0);
            EloamImageList tempImageList = (EloamImageList)global.CreateImageList();
            if (tempImageList != null && tempImage != null && tempImage2 != null)
            {
                hasClickOcrList = true;

                tempImageList.Add(tempImage);
                tempImageList.Add(tempImage2);
                global.DiscernOcrList(1, tempImageList);//异步
            }
            else
            {
                MessageBox.Show("视频未打开");
            }
        }


        private void button_StartIdCardRead_Click(object sender, EventArgs e)
        {
            global.DiscernIdCard();
        }
        //private void button_StartIdCardRead_Click(object sender, EventArgs e)
        //{
        //    global.DiscernIdCard();
        //}
        private void button_StopReadIDCard_Click(object sender, EventArgs e)
        {
            global.StopIdCardDiscern();
        }
        //private void button_StopReadIDCard_Click(object sender, EventArgs e)
        //{
        //    global.StopIdCardDiscern();
        //}
        private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            var count = brs.tb_Bidder.Where(p => p.ISID.ToString() == CompCode).Count();
            //var count = brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Count();
            if (count > 0)
            {

                MessageBox.Show("此信息已存在！");
            }
            else
                MessageBox.Show("暂无此信息！");
        }

        private void button2_Click(object sender, EventArgs e)
        {

            int ok = 0;
            int PersonCount = 0;
            int bidid = 0;
            int status = 0;
            //if (Comp != "" && CompCode != "") // ///投标人名称,组织机构代码  不为空
            if (Comp != "") // ///投标人名称  不为空
            {

                tb_Bidder bid = new tb_Bidder()
                {
                    Company = Comp.ToString(),
                    //CompanyCode = "",
                    CreateDate = DateTime.Now,
                    IsBlack = false,
                    BlackNote = "",
                    FilePath = pictureSavePath.Text// BidderPath
                };
                if (brs.tb_Bidder.Where(p => p.Company == Comp).Count() == 0)
                {
                    status = 0;
                    //brs.tb_Bidder.Where(p => p.CompanyCode == CompCode && (DateTime.Now - p.CreateDate).Days > 0).Count() > 0 ||
                    brs.tb_Bidder.Add(bid);
                    var up = brs.SaveChanges();
                    if (up > 0)
                    {
                        tb_ProjectDetail pj = new tb_ProjectDetail()
                        {
                            ProjectCode = comboBox1.SelectedValue.ToString(),
                            CompanyCode = bid.ISID.ToString(),
                            CreateDate = DateTime.Now
                        };
                        brs.tb_ProjectDetail.Add(pj);
                        var ad = brs.SaveChanges();
                        if (ad > 0)
                        {
                            bidid = bid.ISID;
                            //MessageBox.Show("新增成功！");
                            //this.button_StartIdCardRead.Enabled = true;
                        }
                    }
                    else
                    {
                        MessageBox.Show("新增失败！");
                    }
                }
                else if (brs.tb_Bidder.Where(p => p.Company == Comp).Count() >= 1)
                {
                    //brs.tb_Bidder.Where(p => p.CompanyCode == CompCode && (DateTime.Now - p.CreateDate).Days > 0).Count() > 0 ||
                    tb_Bidder tb_bidder = brs.tb_Bidder.Where(p => p.Company == Comp).FirstOrDefault();
                    bidid = tb_bidder.ISID;
                    //var up = brs.SaveChanges();
                    //if (up > 0)
                    {
                        tb_ProjectDetail pj = new tb_ProjectDetail()
                        {
                            ProjectCode = comboBox1.SelectedValue.ToString(),
                            CompanyCode = tb_bidder.ISID.ToString(),
                            CreateDate = DateTime.Now
                        };
                        brs.tb_ProjectDetail.Add(pj);
                        var ad = brs.SaveChanges();
                        if (ad > 0)
                        {
                            //MessageBox.Show("新增成功！");
                            //this.button_StartIdCardRead.Enabled = true;
                        }
                        else
                        {
                            MessageBox.Show("新增失败！");
                        }
                    }

                }
                //int bidid = bid.ISID;
                //if (bidid == 0)
                //{
                //    bidid = brs.tb_Bidder.Where(p => p.ISID.ToString() == CompCode).Select(p => p.ISID).FirstOrDefault();
                //}


                if (CorpName != "" && CorpIdCode != "")//法定代表人&& CorpPhone != ""
                {
                    BidderInfo corps = new BidderInfo
                    {
                        Name = CorpName,
                        IDCode = CorpIdCode,
                        Phone = CorpPhone,
                        BidderType = "法定代表人",
                        ProjectCode = comboBox1.SelectedValue.ToString(),
                        CreateDate = DateTime.Now


                    };
                    //if (brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Count() > 0)
                    {


                        brs.BidderInfo.Add(corps);
                        //brs.SaveChanges();

                        BBInfo bb1 = new BBInfo()
                        {
                            BidderId = bidid,// bid.ISID,
                            BidderInfoId = corps.Id

                        };
                        brs.BBInfo.Add(bb1);
                        ok = brs.SaveChanges();
                        //MessageBox.Show(corps.Id.ToString() + bid.ISID);

                    };
                    PersonCount += 1;
                    //bid.BBInfo.Add(corps);
                }
                if (CompChargeName != "" && CompChargeIdCode != "")// && CompChargePhone != ""
                {
                    BidderInfo CompCharges = new BidderInfo
                    {
                        Name = CompChargeName,
                        IDCode = CompChargeIdCode,
                        Phone = CompChargePhone,
                        BidderType = "企业负责人",
                        ProjectCode = comboBox1.SelectedValue.ToString(),
                        CreateDate = DateTime.Now
                    };
                    //if (brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Count() > 0)
                    {
                        //var bidid = brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Select(p => p.ISID).FirstOrDefault();
                        brs.BidderInfo.Add(CompCharges);
                        BBInfo bb2 = new BBInfo()
                        {
                            BidderId = bidid,
                            BidderInfoId = CompCharges.Id
                        };
                        brs.BBInfo.Add(bb2);
                        ok = brs.SaveChanges();

                    };
                    PersonCount += 1;

                }
                if (CompTechName != "" && CompTechIdCode != "")//企业技术负责人 && CompTechPhone != ""
                {
                    BidderInfo CompTechs = new BidderInfo
                    {
                        Name = CompTechName,
                        IDCode = CompTechIdCode,
                        Phone = CompTechPhone,
                        BidderType = "企业技术负责人",
                        ProjectCode = comboBox1.SelectedValue.ToString(),
                        CreateDate = DateTime.Now
                    };
                    //if (brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Count() > 0)
                    {
                        //var bidid = brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Select(p => p.ISID).FirstOrDefault();
                        brs.BidderInfo.Add(CompTechs);
                        BBInfo bb3 = new BBInfo()
                        {
                            BidderId = bidid,
                            BidderInfoId = CompTechs.Id
                        };
                        brs.BBInfo.Add(bb3);
                        ok = brs.SaveChanges();

                    };
                    PersonCount += 1;

                }
                if (ProjectChargeName != "" && ProjectChargeIdCode != "")//项目负责人&& ProjectChargePhone != ""
                {
                    BidderInfo ProjectCharges = new BidderInfo
                    {
                        Name = ProjectChargeName,
                        IDCode = ProjectChargeIdCode,
                        Phone = ProjectChargePhone,
                        BidderType = "项目负责人",
                        ProjectCode = comboBox1.SelectedValue.ToString(),
                        CreateDate = DateTime.Now
                    };
                    //if (brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Count() > 0)
                    {
                        //var bidid = brs.tb_Bidder.Where(p => p.CompanyCode == CompCode).Select(p => p.ISID).FirstOrDefault();
                        brs.BidderInfo.Add(ProjectCharges);
                        BBInfo bb4 = new BBInfo()
                        {
                            BidderId = bidid,
                            BidderInfoId = ProjectCharges.Id
                        };
                        brs.BBInfo.Add(bb4);
                        ok = brs.SaveChanges();

                    };
                    PersonCount += 1;
                }
                if (ok != 0)
                {
                    MessageBox.Show("新增成功！请继续添加" + PersonCount + "个登记人信息！点击“特定人员”下的按钮。");
                    if (!String.IsNullOrEmpty(this.textBox3.Text)) button4.Enabled = true;
                    if (!String.IsNullOrEmpty(this.textBox6.Text)) button5.Enabled = true;
                    if (!String.IsNullOrEmpty(this.textBox9.Text)) button11.Enabled = true;
                    if (!String.IsNullOrEmpty(this.textBox12.Text)) button12.Enabled = true;
                    //this.button2.Enabled = false;
                }
                //button4.Enabled = true;
                //button5.Enabled = true;
                //button11.Enabled = true;
                //button12.Enabled = true;


            }

            //MessageBox.Show(comboBox1.SelectedValue.ToString());


        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (this.dataGridView1.CurrentRow.Index > 0)
            {
                string data = this.dataGridView1.CurrentRow.Cells["ISID"].Value.ToString();//datagridview的isid
                if (data != "")
                {
                    int GetData = int.Parse(data);
                    if (dataGridView1.Columns[e.ColumnIndex].Name == "Detail")//查询详情
                    {
                        BidderListfrm bidderlist = new BidderListfrm(GetData);
                        bidderlist.ShowDialog();

                    }
                    if (dataGridView1.Columns[e.ColumnIndex].Name == "RelateProject")//查询相关项目
                    {
                        var code = brs.tb_Bidder.Find(GetData);
                        var list = brs.tb_ProjectDetail.Where(p => p.CompanyCode == code.ISID.ToString()).Select(p => p.ProjectCode).ToList();
                        var prolist = brs.tb_Project.Where(p => list.Contains(p.ProjectCode)).ToList();
                        frmProjectList frmpro = new frmProjectList(prolist);
                        frmpro.ShowDialog();

                    }

                }
            }


        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView2.CurrentRow.Cells["projectid"].Value != null)
            {
                string data = this.dataGridView2.CurrentRow.Cells["projectid"].Value.ToString();//查询项目相关的信息  投标人 
                int GetData = int.Parse(data);
                if (dataGridView2.Columns[e.ColumnIndex].Name == "Update")//查询详情
                {

                    UpdateProject project = new UpdateProject(GetData);
                    project.ShowDialog();

                }
                else
                {
                    frmProjectBidder pb = new frmProjectBidder(GetData);
                    pb.ShowDialog();
                }
            }




        }

        private void button5_Click(object sender, EventArgs e)
        {
            AddProject addp = new AddProject(people);//添加项目
            addp.ShowDialog();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            dgv1binds();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            dgv2binds();
        }

        private void button8_Click_1(object sender, EventArgs e)
        {
            //this.button_StartIdCardRead.Enabled = true;
        }

        private void 项目管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.tabControl1.SelectedTab = tabPage3;
        }

        private void groupBox5_Enter(object sender, EventArgs e)
        {


        }


        private void dGVUser_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //    string data = this.dataGridView1.CurrentRow.Cells["ISID"].Value.ToString();//datagridview的isid
            //    int GetData = int.Parse(data);

            int b = (int)this.dGVUser.CurrentRow.Cells["userid"].Value;
            if (dGVUser.Columns[e.ColumnIndex].Name == "userchange")//查询详情
            {
                var user = brs.Users.Find(b);
                Userfrm userfrm = new Userfrm(user);
                userfrm.ShowDialog();

            }
            else
            {
                var list = brs.Roles.ToList();
                var have = brs.UserRoles.Where(p => p.uid == b).ToList();
                //var hasright = brs.Roles.Include(Right).ToList();
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("序号", typeof(string));
                dt.Columns.Add("角色名称", typeof(string));
                dt.Columns.Add("是否可用", typeof(bool));

                foreach (var p in list)
                {

                    DataRow dr = dt.NewRow();
                    dr["序号"] = p.Id;
                    dr["角色名称"] = p.Name;
                    dr["是否可用"] = have.Exists(a => a.rid == p.Id);//false;// p.AddTime;
                    dt.Rows.Add(dr);
                }
                dt.AcceptChanges();

                this.dGVUserRole.DataSource = dt;
            }

        }
        private void dGVRole_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // int a=dataGridView1.CurrentRow.Index;
            //var b=dataGridView1.Rows[a].Cells["Id"].Value;
            int b = (int)this.dGVRole.CurrentRow.Cells["roleid"].Value;
            var list = brs.Rights.ToList();
            var have = brs.RoleRights.Where(p => p.rid == b).ToList();
            //var hasright = brs.Roles.Include(Right).ToList();
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("序号", typeof(string));
            dt.Columns.Add("功能名称", typeof(string));
            dt.Columns.Add("模块名称", typeof(string));
            dt.Columns.Add("窗体", typeof(string));
            dt.Columns.Add("按钮", typeof(string));
            dt.Columns.Add("是否可用", typeof(bool));

            foreach (var p in list)
            {

                DataRow dr = dt.NewRow();
                dr["序号"] = p.Id;
                dr["功能名称"] = p.Name;
                dr["模块名称"] = p.Module;
                dr["窗体"] = p.Frm;//.Enabled?"是":"否";
                dr["按钮"] = p.btn;
                dr["是否可用"] = have.Exists(a => a.riid == p.Id);//false;// p.AddTime;
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            this.dGVRoleRight.DataSource = dt;
            //MessageBox.Show(b.ToString());//int roleid =(int)

        }
        private void dGVUserRole_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            if (grid != null)
            {
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }
        private void dGVUser_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }
        private void dGVUserRole_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int userid = (int)this.dGVUser.CurrentRow.Cells[0].Value;
            DataGridView grid = sender as DataGridView;
            if (grid != null && e.RowIndex >= 0)
            {
                //if (grid.Columns[e.ColumnIndex].HeaderText == "是否可用")
                if (grid.Columns[e.ColumnIndex].Index == 2)
                {
                    DataTable dt = grid.DataSource as DataTable;
                    int pstnID = Convert.ToInt32(dt.Rows[e.RowIndex][0]);
                    UserRoles rr = new UserRoles()
                    {
                        uid = userid,
                        rid = pstnID,
                        IsDel = false,
                        AddTime = DateTime.Now

                    };
                    DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 获得checkbox列单元格
                    int result = 0;
                    //////如下部分是对中间表userrole的增添功能

                    if (checkbox != null && checkbox.Value.ToString() == "True")
                    {
                        var urs = brs.UserRoles.Where(p => p.uid == userid && p.rid == pstnID).ToList();
                        brs.UserRoles.RemoveRange(urs);
                        result = brs.SaveChanges();
                        // 
                        if (brs.UserRoles.Where(p => p.uid == userid && p.rid == pstnID).Count() == 0)
                            brs.UserRoles.Add(rr);
                        result = brs.SaveChanges();

                    }//////如下部分是对中间表userrole的增添功能
                    else if (checkbox != null && checkbox.Value.ToString() == "False")
                    {
                        if (brs.UserRoles.Where(p => p.uid == userid && p.rid == pstnID).Count() > 0)
                        {
                            var rrts = brs.UserRoles.Where(p => p.uid == userid && p.rid == pstnID).FirstOrDefault();
                            brs.UserRoles.Remove(rrts);
                            result = brs.SaveChanges();
                        }


                    }
                    if (result < 1)
                    {
                        //MessageBox.Show(pstnID.ToString() + roleid.ToString());
                        MessageBox.Show(" 修改失败", " 提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void dGVRight_AllowUserToAddRowsChanged(object sender, EventArgs e)
        {
            //this.dGVRight.Rows..ColumnAdded();
        }

        private void AddRight_Click(object sender, EventArgs e)
        {
            Rightfrm rfrm = new Rightfrm();
            rfrm.ShowDialog();

        }

        private void button8_Click_2(object sender, EventArgs e)
        {
            dGVRight.DataSource = brs.Rights.ToList();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            Rolefrm role = new Rolefrm();
            role.ShowDialog();
        }

        private void button10_Click(object sender, EventArgs e)
        {

        }

        private void dGVRoleRight_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //   bool b = (bool)this.dGVRoleRight.CurrentRow.Cells[5].Value;
            //   //bool c = (bool)this.dGVRoleRight.SelectedCells.Cells[5].Value;
            //if( e.ColumnIndex==5)   MessageBox.Show(b.ToString()); 

        }
        //private void dGVRoleRight_CellContentClick(object sender, DataGridViewCellEventArgs e)
        //{
        // //   bool b = (bool)this.dGVRoleRight.CurrentRow.Cells[5].Value;
        // //   //bool c = (bool)this.dGVRoleRight.SelectedCells.Cells[5].Value;
        // //if( e.ColumnIndex==5)   MessageBox.Show(b.ToString()); 

        //}

        private void dGVRoleRight_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            if (grid != null)
            {
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        #region 在角色管理里选中role对其进行权限增减
        private void dGVRoleRight_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int roleid = (int)this.dGVRole.CurrentRow.Cells[0].Value;
            DataGridView grid = sender as DataGridView;
            if (grid != null && e.RowIndex >= 0)
            {
                //if (grid.Columns[e.ColumnIndex].HeaderText == "是否可用")
                if (grid.Columns[e.ColumnIndex].Index == 5)
                {
                    DataTable dt = grid.DataSource as DataTable;
                    int pstnID = Convert.ToInt32(dt.Rows[e.RowIndex][0]);
                    RoleRights rr = new RoleRights()
                    {
                        rid = roleid,
                        riid = pstnID,
                        AddTime = DateTime.Now

                    };
                    DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 获得checkbox列单元格
                    int result = 0;
                    if (checkbox != null && checkbox.Value.ToString() == "True")
                    {
                        var rrts = brs.RoleRights.Where(p => p.rid == roleid && p.riid == pstnID).ToList();
                        brs.RoleRights.RemoveRange(rrts);
                        result = brs.SaveChanges();
                        // 
                        if (brs.RoleRights.Where(p => (p.rid == roleid && p.riid == pstnID)).Count() == 0)
                            brs.RoleRights.Add(rr);
                        result = brs.SaveChanges();

                    }
                    else if (checkbox != null && checkbox.Value.ToString() == "False")
                    {
                        if (brs.RoleRights.Where(p => p.rid == roleid && p.riid == pstnID).Count() > 0)
                        {
                            var rrts = brs.RoleRights.Where(p => p.rid == roleid && p.riid == pstnID).FirstOrDefault();
                            brs.RoleRights.Remove(rrts);
                            result = brs.SaveChanges();
                        }


                    }
                    if (result < 1)
                    {
                        //MessageBox.Show(pstnID.ToString() + roleid.ToString());
                        MessageBox.Show(" 修改失败", " 提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

        }
        #endregion

        private void button10_Click_1(object sender, EventArgs e)
        {
            AddUser userfrm = new AddUser();
            userfrm.ShowDialog();

        }

        private void SearchPro_Click(object sender, EventArgs e)
        {
            if (this.txtBoxProjectName.Text != "")
                dataGridView2.DataSource = brs.tb_Project.Where(p => p.ProjectName.Contains(txtBoxProjectName.Text)).ToList();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox15.Text != "")
            {
                //var list =Select a in brs.tb_Bidder..Where(p=>p.ToString().) 
                dataGridView1.DataSource = brs.tb_Bidder.Where(p => p.Company.Contains(textBox15.Text)).OrderBy(p => p.CreateDate).ToList();
            }
        }

        private void bidderExcel_Click(object sender, EventArgs e)
        {
            //List<tb_Bidder> list = List <tb_Bidder> dataGridView1.Rows;
            var list = brs.tb_Bidder.ToList();
            GenerateExcel(list);
        }
        public void GenerateExcel(List<tb_Bidder> list)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("编号", typeof(string));
            dt.Columns.Add("公司名称", typeof(string));
            dt.Columns.Add("公司编码", typeof(string));
            //dt.Columns.Add("法人代表", typeof(string));
            //dt.Columns.Add("法人代表身份证", typeof(string));
            //dt.Columns.Add("手机号码", typeof(string));
            dt.Columns.Add("新建日期", typeof(string));
            //dt.Columns.Add("是否是黑名单", typeof(bool?));
            foreach (var p in list)
            {

                DataRow dr = dt.NewRow();
                dr["编号"] = p.ISID;
                dr["公司名称"] = p.Company;
                //dr["公司编码"] = p.CompanyCode;
                //dr["法人代表"] = p.CorporationName;
                //dr["法人代表身份证"] = p.CorporationID;
                //dr["手机号码"] = p.Phone;
                dr["新建日期"] = p.CreateDate;
                //dr["是否是黑名单"] = p.IsBlack.Value ? "是" : "否";

                dt.Rows.Add(dr);
            }
            //dt.AcceptChanges();
            //ExportExcel(dt);
        }
        //public void ExportExcel(System.Data.DataTable dt)
        //{
        //    if (dt == null || dt.Rows.Count == 0) return;
        //    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        //    if (xlApp == null)
        //    {
        //        return;
        //    }
        //    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
        //    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
        //    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
        //    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
        //    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
        //    Microsoft.Office.Interop.Excel.Range range;
        //    long totalCount = dt.Rows.Count;
        //    long rowRead = 0;
        //    float percent = 0;
        //    for (int i = 0; i < dt.Columns.Count; i++)
        //    {
        //        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        //        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
        //        range.Interior.ColorIndex = 15;
        //        range.Font.Bold = true;
        //    }
        //    for (int r = 0; r < dt.Rows.Count; r++)
        //    {
        //        for (int i = 0; i < dt.Columns.Count; i++)
        //        {
        //            worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
        //        }
        //        rowRead++;
        //        percent = ((float)(100 * rowRead)) / totalCount;
        //    }
        //    xlApp.Visible = true;
        //}

        private void 软件说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请先连接好高拍仪之后再打开此软件！进行文字识别时保持台面仅放有文档，位置端正，文档在摄像视野内。");
        }

        //
        private void button4_Click_1(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox3.Text))
            {
                if (button4.BackColor == SystemColors.Control)
                {
                    if (textBox4.Text.Length == 18)
                    {
                        var date = DateTime.Now.Date;
                        var list = brs.BidderInfo.Where(p => p.IDCode == textBox4.Text && p.CreateDate < date).OrderByDescending(p => p.CreateDate).ToList();
                        if (list.Count > 0)
                        {
                            MessageBox.Show("发现存在疑似相同的该“特定人员”信息！");
                            var bider = list.First();
                            frmBidderDetail bidder = new frmBidderDetail(bider.Id);
                            bidder.ShowDialog();
                        }

                    }
                    if (selectDevice.SelectedIndex == 1)
                    {
                        openVideo_Click(sender, e);
                    }
                    switch (CurrentSelect)
                    {
                        case 1: if (progressBar1.Value == 100) button4.Enabled = false; break;
                        case 2: if (progressBar2.Value == 100) button5.Enabled = false; break;
                        case 3: if (progressBar3.Value == 100) button11.Enabled = false; break;
                        case 4: if (progressBar4.Value == 100) button12.Enabled = false; break;

                    }
                    button4.BackColor = Color.Red;
                    Identityproof = button4.Text + textBox3.Text;
                    progressBar1.Visible = true;
                    CurrentSelect = 1;//切换当前选择的状态s
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("请放置好该特定人员的身份证明文件?", "确定", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        shoot_Click(sender, e);
                    }

                }
                else
                {
                    button4.BackColor = SystemColors.Control;
                    Identityproof = "";
                }

            }

        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox6.Text))
            {
                if (button5.BackColor == SystemColors.Control)
                {
                    if (textBox7.Text.Length == 18)
                    {
                        var date = DateTime.Now.Date;
                        var list = brs.BidderInfo.Where(p => p.IDCode == textBox4.Text && p.CreateDate < date).OrderByDescending(p => p.CreateDate).ToList();
                        //var list = brs.BidderInfo.Where(p => p.IDCode == textBox7.Text).OrderByDescending(p => p.CreateDate).ToList();
                        if (list.Count > 0)
                        {
                            MessageBox.Show("发现存在该“特点人员”信息！");
                            var bider = list.First();
                            frmBidderDetail bidder = new frmBidderDetail(bider.Id);
                            bidder.ShowDialog();
                        }

                    }
                    if (selectDevice.SelectedIndex == 1)
                    {
                        openVideo_Click(sender, e);
                    }
                    switch (CurrentSelect)
                    {
                        case 1: if (progressBar1.Value == 100) button4.Enabled = false; break;
                        case 2: if (progressBar2.Value == 100) button5.Enabled = false; break;
                        case 3: if (progressBar3.Value == 100) button11.Enabled = false; break;
                        case 4: if (progressBar4.Value == 100) button12.Enabled = false; break;
                    }
                    button5.BackColor = Color.Red;
                    Identityproof = button5.Text + textBox6.Text;
                    progressBar2.Visible = true;
                    CurrentSelect = 2;
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("请放置好该特定人员的身份证明文件?", "确定", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        shoot_Click(sender, e);
                    }
                }
                else
                {
                    button5.BackColor = SystemColors.Control;
                    Identityproof = "";
                }

            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox9.Text))
            {
                if (button11.BackColor == SystemColors.Control)
                {
                    if (textBox10.Text.Length == 18)
                    {
                        var date = DateTime.Now.Date;
                        var list = brs.BidderInfo.Where(p => p.IDCode == textBox4.Text && p.CreateDate < date).OrderByDescending(p => p.CreateDate).ToList();
                        //var list = brs.BidderInfo.Where(p => p.IDCode == textBox10.Text).OrderByDescending(p => p.CreateDate).ToList();
                        if (list.Count > 0)
                        {
                            MessageBox.Show("发现存在该“特点人员”信息！");
                            var bider = list.First();
                            frmBidderDetail bidder = new frmBidderDetail(bider.Id);
                            bidder.ShowDialog();
                        }

                    }
                    if (selectDevice.SelectedIndex == 1)
                    {
                        openVideo_Click(sender, e);
                    }
                    switch (CurrentSelect)
                    {
                        case 1: if (progressBar1.Value == 100) button4.Enabled = false; break;
                        case 2: if (progressBar2.Value == 100) button5.Enabled = false; break;
                        case 3: if (progressBar3.Value == 100) button11.Enabled = false; break;
                        case 4: if (progressBar4.Value == 100) button12.Enabled = false; break;

                    }
                    button11.BackColor = Color.Red;
                    Identityproof = button11.Text + textBox9.Text;
                    progressBar3.Visible = true;
                    CurrentSelect = 3;
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("请放置好该特定人员的身份证明文件?", "确定", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        shoot_Click(sender, e);
                    }
                }
                else
                {
                    button11.BackColor = SystemColors.Control;
                    Identityproof = "";
                }


            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox12.Text))
            {
                if (button12.BackColor == SystemColors.Control)
                {
                    if (textBox13.Text.Length == 18)
                    {
                        //DateTime.
                        //var list = brs.BidderInfo.Where(p => p.IDCode == textBox13.Text || p.Name == textBox12.Text).OrderByDescending(p => p.CreateDate).ToList();
                        //var list = brs.BidderInfo.Where(p => p.IDCode == textBox13.Text).OrderByDescending(p => p.CreateDate).ToList();
                        var date = DateTime.Now.Date;
                        var list = brs.BidderInfo.Where(p => p.IDCode == textBox4.Text && p.CreateDate < date).OrderByDescending(p => p.CreateDate).ToList();
                        if (list.Count > 0)
                        {
                            MessageBox.Show("发现存在该“特点人员”信息！");
                            var bider = list.First();
                            frmBidderDetail bidder = new frmBidderDetail(bider.Id);
                            bidder.ShowDialog();
                        }

                    }

                    if (selectDevice.SelectedIndex == 1)
                    {
                        openVideo_Click(sender, e);
                    }
                    switch (CurrentSelect)
                    {
                        case 1: if (progressBar1.Value == 100) button4.Enabled = false; break;
                        case 2: if (progressBar2.Value == 100) button5.Enabled = false; break;
                        case 3: if (progressBar3.Value == 100) button11.Enabled = false; break;
                        case 4: if (progressBar4.Value == 100) button12.Enabled = false; break;

                    }
                    button12.BackColor = Color.Red;
                    Identityproof = button12.Text + textBox12.Text;
                    progressBar4.Visible = true;
                    CurrentSelect = 4;
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("请放置好该特定人员的身份证明文件?", "确定", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        shoot_Click(sender, e);
                    }
                }
                else
                {
                    button12.BackColor = SystemColors.Control;
                    Identityproof = "";
                }


            }
        }

        private void button13_Click(object sender, EventArgs e)
        {

            ///
            /////
            ///完成后的初始化变量
            if (
                  ((progressBar1.Visible == true && progressBar1.Value == 100) || String.IsNullOrEmpty(this.textBox3.Text))//确认完成每个操作
                && ((progressBar2.Visible == true && progressBar2.Value == 100) || String.IsNullOrEmpty(this.textBox6.Text))
                && ((progressBar3.Visible == true && progressBar3.Value == 100) || String.IsNullOrEmpty(this.textBox9.Text))
                && ((progressBar4.Visible == true && progressBar4.Value == 100) || String.IsNullOrEmpty(this.textBox12.Text))
                )
            {
                button4.BackColor = SystemColors.Control;
                button5.BackColor = SystemColors.Control;
                button11.BackColor = SystemColors.Control;
                button12.BackColor = SystemColors.Control;
                button4.Enabled = false;
                button5.Enabled = false;
                button11.Enabled = false;
                button12.Enabled = false;

                progressBar1.Value = 0; progressBar1.Visible = false;
                progressBar2.Value = 0; progressBar2.Visible = false;
                progressBar3.Value = 0; progressBar3.Visible = false;
                progressBar4.Value = 0; progressBar4.Visible = false;
                //表格清零
                textBox1.Text = "";
                //textBox2.Text = "";
                textBox3.Text = "";
                textBox4.Text = "";
                textBox5.Text = "";
                textBox6.Text = "";
                textBox7.Text = "";
                textBox8.Text = "";
                textBox9.Text = "";
                textBox10.Text = "";
                textBox11.Text = "";
                textBox12.Text = "";
                textBox13.Text = "";
                textBox14.Text = "";

                picturename = "";
                docname = "";
                Comp = "";   //企业名称
                CompCode = "";   //企业编号 
                Corp = "";   ///法人代表       
                IDCODE = ""; ////法人证件      
                Pho = ""; ///手机号码  这是字符串结尾
                //法定代表人Corp
                CorpName = "";
                CorpIdCode = "";
                CorpPhone = "";
                //企业负责人CompCharge
                CompChargeName = "";
                CompChargeIdCode = "";
                CompChargePhone = "";
                //企业技术负责人CompTech       
                CompTechName = "";
                CompTechIdCode = "";
                CompTechPhone = "";
                //项目负责人ProjectCharge
                ProjectChargeName = "";
                ProjectChargeIdCode = "";
                ProjectChargePhone = "";
                BidderPath = "";   ///投标人信息文件路径
                Idfile = "";//身份证图片路径
                Identityproof = "";//身份证明地址
                IdproPicture = "";
                openVideo_Click(sender, e);
                MessageBox.Show("您已经完成该单位的录入工作！");
                button13.Enabled = false;
            }
            else MessageBox.Show("你好像还有步骤没做完哦！");
        }

        private void button14_Click(object sender, EventArgs e)
        { ///
            /////
            ///清零的初始化变量

            button4.BackColor = SystemColors.Control;
            button5.BackColor = SystemColors.Control;
            button11.BackColor = SystemColors.Control;
            button12.BackColor = SystemColors.Control;
            button4.Enabled = false;
            button5.Enabled = false;
            button11.Enabled = false;
            button12.Enabled = false;
            button13.Enabled = false;

            progressBar1.Value = 0; progressBar1.Visible = false;
            progressBar2.Value = 0; progressBar2.Visible = false;
            progressBar3.Value = 0; progressBar3.Visible = false;
            progressBar4.Value = 0; progressBar4.Visible = false;
            //表格清零
            textBox1.Text = "";
            //textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
            textBox8.Text = "";
            textBox9.Text = "";
            textBox10.Text = "";
            textBox11.Text = "";
            textBox12.Text = "";
            textBox13.Text = "";
            textBox14.Text = "";

            picturename = "";
            docname = "";
            Comp = "";   //企业名称
            CompCode = "";   //企业编号 
            Corp = "";   ///法人代表       
            IDCODE = ""; ////法人证件      
            Pho = ""; ///手机号码  这是字符串结尾
            //法定代表人Corp
            CorpName = "";
            CorpIdCode = "";
            CorpPhone = "";
            //企业负责人CompCharge
            CompChargeName = "";
            CompChargeIdCode = "";
            CompChargePhone = "";
            //企业技术负责人CompTech       
            CompTechName = "";
            CompTechIdCode = "";
            CompTechPhone = "";
            //项目负责人ProjectCharge
            ProjectChargeName = "";
            ProjectChargeIdCode = "";
            ProjectChargePhone = "";
            BidderPath = "";   ///投标人信息文件路径
            Idfile = "";//身份证图片路径
            Identityproof = "";//身份证明地址
            IdproPicture = "";


        }

        private void button15_Click(object sender, EventArgs e)//对识别的信息进行修改
        {
            //if ((textBox1.Text != "" && textBox2.Text != "") && (textBox3.Text != "" || textBox6.Text != "" || textBox9.Text != "" || textBox12.Text != ""))
            if ((textBox1.Text != "") && (textBox3.Text != "" || textBox6.Text != "" || textBox9.Text != "" || textBox12.Text != ""))
            {
                Comp = textBox1.Text; //投标人名称
                //CompCode = textBox2.Text; //组织机构代码 
                CorpName = textBox3.Text;//法定代表人
                CorpIdCode = textBox4.Text;
                CorpPhone = textBox5.Text;
                CompChargeName = textBox6.Text;    //企业负责人CompCharge
                CompChargeIdCode = textBox7.Text;
                CompChargePhone = textBox8.Text;
                CompTechName = textBox9.Text;//企业技术负责人CompTech    
                CompTechIdCode = textBox10.Text;
                CompTechPhone = textBox11.Text;
                ProjectChargeName = textBox12.Text;//项目负责人ProjectCharge
                ProjectChargeIdCode = textBox13.Text;
                ProjectChargePhone = textBox14.Text;
            }


        }

        private void 关于软件使用的若干问题ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1.确认连接好高拍仪，如果未连接请连接好后重启此软件。\n2.选择好当前项目，方可进行操作。放置好登记表格，打开摄像头，待其显示清晰，方可点击“文字识别”。\n3.文字识别完成后，对其进行检验，确认无误后，可以下一步。\n4.拍摄留档登记表。\n5.新增此单位信息。\n6.对当前的特定人员进行录入操作\n7.身份证明录入\n8.二代证录入\n9.现场照片录入。\n10.确认录入人员全部录入后可点击完成，结束此次该单位的录入工作。\n11.正式使用系统前，请做好相关准备工作。");
        }

        private void 设置文件默认存储位置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            if (path.SelectedPath != "")
            {
                Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["filepath"].Value = path.SelectedPath + "/";//注意路径没有斜杠
                config.Save();
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                this.pictureSavePath.Text = path.SelectedPath;
            }


        }


        private void button16_Click(object sender, EventArgs e)
        {
            //if (!String.IsNullOrEmpty(textBox1.Text) || !String.IsNullOrEmpty(textBox2.Text))
            if (!String.IsNullOrEmpty(textBox1.Text))
            {
                int bidid = brs.tb_Bidder.Where(p => p.Company == textBox1.Text).OrderBy(p => p.CreateDate).Select(p => p.ISID).FirstOrDefault();
                if (bidid > 0)
                {
                    BidderListfrm bidlist = new BidderListfrm(bidid);
                    bidlist.ShowDialog();
                }
                else MessageBox.Show("无历史记录！");



            }
        }

        private void shootlive_Click(object sender, EventArgs e)
        {

        }

        private void openCam_Click(object sender, EventArgs e)
        {
            selectDevice.SelectedIndex = 1;
            int devIdx = 1;// selectDevice.SelectedIndex;
            resIdx = 6;
            //modeIdx = selectMode.Text == "YUY2" ? 1 : 2;
            int modeIdx = 1;
            if (devIdx == 1) modeIdx = 2;
            if (-1 != devIdx)
            {
                if (null != video)
                {
                    video.Destroy();
                    video = null;
                }

                EloamDevice tempDevice = deviceList[devIdx];
                video = (EloamVideo)tempDevice.CreateVideo(resIdx, modeIdx);

                if (null != video)
                {
                    eloamView.SelectVideo(video);
                    eloamView.SetText("打开视频中，请等待...", RGB(255, 255, 255));

                    selectDevice.Enabled = false;
                    //selectResolution.Enabled = false;
                    //selectMode.Enabled = false;
                    //openCam.Enabled = false;
                    openVideo.Enabled = true;
                    closeVideo.Enabled = true;
                }
                MessageBoxButtons messButton = MessageBoxButtons.OK;
                DialogResult dr = MessageBox.Show("准备拍摄现场照片，准备好了吗?", "确认", messButton);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {
                    this.shoot_Click(sender, e);
                }

            }
        }
        //private void openCam_Click(object sender, EventArgs e)
        //{
        //    selectDevice.SelectedIndex = 1;
        //    int devIdx = 1;// selectDevice.SelectedIndex;
        //    resIdx = 6;
        //    //modeIdx = selectMode.Text == "YUY2" ? 1 : 2;
        //    int modeIdx = 1;
        //    if (devIdx == 1) modeIdx = 2;
        //    if (-1 != devIdx)
        //    {
        //        if (null != video)
        //        {
        //            video.Destroy();
        //            video = null;
        //        }

        //        EloamDevice tempDevice = deviceList[devIdx];
        //        video = (EloamVideo)tempDevice.CreateVideo(resIdx, modeIdx);

        //        if (null != video)
        //        {
        //            eloamView.SelectVideo(video);
        //            eloamView.SetText("打开视频中，请等待...", RGB(255, 255, 255));

        //            selectDevice.Enabled = false;
        //            //selectResolution.Enabled = false;
        //            //selectMode.Enabled = false;
        //            //openCam.Enabled = false;
        //            openVideo.Enabled = true;
        //            closeVideo.Enabled = true;
        //        }
        //        this.shoot_Click(sender, e);
        //    }
        //}
        private void groupebox8_Enter(object sender, EventArgs e)
        {

        }

        private void 演示视频ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GuideVideo gv = new GuideVideo();
            gv.Show();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            dgv3binds();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            if (txt_TenderMsgName.Text != "")
            {
                dGVTender.DataSource = brs.TenderMsg.Where(p => p.Name.Contains(txt_TenderMsgName.Text)).OrderBy(p => p.AddTime).ToList();
            }
        }

        private void txtAddTender_Click(object sender, EventArgs e)
        {
            AddTender at = new AddTender();
            at.Show();
        }

        private void dGVTender_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (this.dGVTender.CurrentRow.Index > 0)
            {
                string data = this.dGVTender.CurrentRow.Cells["Id"].Value.ToString();//datagridview的isid
                if (data != "")
                {
                    int GetData = int.Parse(data);
                    if (dGVTender.Columns[e.ColumnIndex].Name == "change")//查询详情
                    {
                        UpdateTender uptender = new UpdateTender(GetData);
                        uptender.ShowDialog();

                    }
                    if (dGVTender.Columns[e.ColumnIndex].Name == "delete")//查询相关项目
                    {
                        var tender = brs.TenderMsg.Find(GetData);
                        if (tender != null)
                        {
                            brs.TenderMsg.Remove(tender);
                            if (brs.SaveChanges() > 0)
                                MessageBox.Show("已执行删除操作！");
                            else MessageBox.Show("删除失败！");
                        }

                        //var code = brs.tb_Bidder.Find(GetData);
                        //var list = brs.tb_ProjectDetail.Where(p => p.CompanyCode == code.CompanyCode).Select(p => p.ProjectCode).ToList();
                        //var prolist = brs.tb_Project.Where(p => list.Contains(p.ProjectCode)).ToList();
                        //frmProjectList frmpro = new frmProjectList(prolist);
                        //frmpro.ShowDialog();

                    }

                }
            }
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            dGVUser.DataSource = brs.Users.AsNoTracking().ToList();
        }

        private void RefRolebtn_Click(object sender, EventArgs e)
        {
            dGVRole.DataSource = brs.Roles.AsNoTracking().ToList();
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserPassword userpwd = new UserPassword(people);
            userpwd.ShowDialog();
        }

        private void frmBid_FormClosed(object sender, FormClosedEventArgs e)
        {
            brs.LoginInfo.Add(new LoginInfo { UserName = people.UserName, UserId = people.UserId, LoginOutTime = DateTime.Now, Client = Dns.GetHostName() });
            brs.SaveChanges();
            System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
        }

    }
}









